#include "winInit.h"
#include "SDL_image.h"
#include "SDL_ttf.h"
#include "SDL_mixer.h"

TT_Bool initWindow(TT_Window *win){
    TT_Bool success = true;
    win->win = NULL;
    win->render = NULL;
    win->texture = NULL;
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0){
        SDL_Log("SDL_Init failed: %s\n", SDL_GetError());
        success = false;
    }else{
        win->win = SDL_CreateWindow("Tetris Game",
                                    SDL_WINDOWPOS_UNDEFINED,
                                    SDL_WINDOWPOS_UNDEFINED,
                                    TT_WINDOW_WIDTH,
                                    TT_WINDOW_HEIGHT,
                                    SDL_WINDOW_OPENGL);
        if(!win->win){
            SDL_Log("SDL_CreateWindow failed: %s\n", SDL_GetError());
            success = false;
        }else{
            win->width = TT_WINDOW_WIDTH;
            win->height = TT_WINDOW_HEIGHT;
            win->render = SDL_CreateRenderer(win->win, -1, SDL_RENDERER_ACCELERATED);
            if(!win->render){
                SDL_Log("SDL_CreateRenderer failed: %s\n", SDL_GetError());
                success = false;
            }

            //init sdl2 image
            int flags = IMG_INIT_JPG|IMG_INIT_PNG;
            int initted = IMG_Init(flags);
            if((initted & flags) != flags) {
                SDL_Log("IMG_Init failed: %s\n", IMG_GetError());
            }

            SDL_Surface *surface = IMG_Load(TT_IMG_PATH"logo.png");
            if(!surface){
                SDL_Log("IMG_Load failed: %s\n", IMG_GetError());
                success = false;
            }
            SDL_SetWindowIcon(win->win, surface);
            SDL_FreeSurface(surface);

            //init sdl2 ttf
            if(TTF_Init() == -1) {
                SDL_Log("TTF_Init failed: %s\n", TTF_GetError());
                success = false;
            }else{
                SDL_Log("TTF_Init OK!\n");
            }

            //Initialize SDL_mixer
            if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) {
                SDL_Log("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
                success = false;
            }else{
                SDL_Log("Mix Open Audio OK!\n");
            }


        }
    }

    return success;
}

